import { BaseService } from '@service/base.service';
import { ResetPasswordComponent } from '@share/component/reset-password/reset-password.component';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzMessageService } from 'ng-zorro-antd/message';
import { LoginService } from '@service/login.service';
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import { environment } from '@env/environment';
import { WesocketService } from '@service/wesocket.service';
import { AuthService } from '@service/auth.service';
import { Auth } from '@app/store/auth.enum';
import { pipe } from 'rxjs';
import { filter } from 'rxjs/operators';

@Component({
	selector: 'app-page',
	templateUrl: './page.component.html',
	styleUrls: ['./page.component.less']
})
export class PageComponent implements OnInit {
	isCollapsed = true;
	userInfo = null;
	isLoading = false;
	tree = [];
	menuList = [];
	noticeList =[];

	authList = [];
	authEnum = Auth;
	noticeNum = 0;
	isMsg = false;
	breadcrumbList= [];
	constructor(
		private loginService: LoginService,
		private nzMessageService: NzMessageService,
		private router: Router,
		private nzModalService: NzModalService,
		private wesocketService: WesocketService,
		private authService: AuthService,
		private baseService: BaseService,
		private route: ActivatedRoute
	) {
		this.authList = this.authService.getAuth();
	}
	get isHome() {
		return location.href.includes('/home')
	}
	ngOnInit() {
		this.init();
		if (this.authList.includes(this.authEnum.NOTICE_VIEW)) {
			this.getNoticeNum();
		}
		this.router.events
		.pipe(
			filter((event) => event instanceof NavigationEnd)
		)
		.subscribe((event:NavigationEnd) => {
			//do something
			const path = event.url;
			this.getBreadcrumb(path);
		});
		

	}

	getBreadcrumb(path: string) {
		const menuList = this.loginService.getMenu();
		const breadcrumbList = [];
		menuList?.forEach(menu => {
			if (menu?.nodes?.length) {
				const res = menu?.nodes.find(it => it?.resUrl === path);
				if (res) {
					menu.icon = this.getIcon([res]);
					breadcrumbList.push(menu, res);
				}
			}
		});
		this.breadcrumbList = breadcrumbList;
		
	}
	
	private async getNoticeNum() {
		const result = await this.baseService.getNoticeNum();
		this.noticeNum = result.data;
		this.isMsg = this.noticeNum > 0;
	}

	initSocket() {
		// this.userInfo.userId
		const url = environment.API_DOMAIN.default + '/websocket/' + this.userInfo.userId ;
		if (this.wesocketService.ws) {
			return;
		}
		this.wesocketService.createObservableSocket(url.replace(/http/g, 'ws').replace(/https/g, 'wss')).subscribe(
			data => {
				this.noticeNum = this.noticeNum + 1;
				this.isMsg = true;
			},
			err => console.error(err),
			() => console.warn("流已经结束") //  最后结束后，会执行到这的
		);
	}

	async init() {
		const pathName = location.hash.replace(/#/g, '');
		this.getBreadcrumb(pathName);
		this.userInfo = this.loginService.getUserInfo();
		this.initSocket();
		const menu = this.loginService.getMenu();
		if (menu) {
			this.tree = menu;
		}
	}



	isChildrenCheck(id: number, treeToList: any[]) {
		const childList = treeToList.filter(it => it.parentId === id);
		if (childList?.length) {
			if (childList.some(itm => itm.check)) {
				return true;
			}
			childList.forEach(item => {
				this.isChildrenCheck(item.id, treeToList);
			});
		}
	}
	async logout() {
		await this.loginService.logout();
		this.nzMessageService.success('退出成功');
		this.loginService.clearUserInfo();
		this.router.navigateByUrl('/login');
	}

	async getNoticeList(val: boolean) {
		if (!val) {
			return;
		}
		this.isMsg = false;
		this.isLoading = true;
		const  result = await this.baseService.getNoticeList({page: 1, limit:30, status: '0' });
		this.noticeList = result.data.list;
		setTimeout(() => {
			this.isLoading = false;
		}, 500);
	}
	resetPassword() {
		const _this = this;
		this.nzModalService.create({
			nzTitle: '更改密码',
			nzContent: ResetPasswordComponent,
			nzWidth: 600,
			nzFooter: null,
			nzOnOk: () => {
				_this.logout();
			}
		})
	}

	listToChildren(list: any[]) {
		if (list) {
			list.forEach(itm => {
				itm.children = itm.list || [];
				itm.id = itm.value * 1;
				if (itm.list?.length) {
					this.listToChildren(itm.list);
				}
			});
		}
	}

	getIcon(menuList: any[]) {
		if (menuList?.length) {
			const menuUrl = menuList[0].resUrl || '';
			if (menuUrl.includes('/system')) {
				return 'appstore';
			}
			if (menuUrl.includes('/grid')) {
				return 'group';
			}
			if (menuUrl.includes('/base')) {
				return 'setting';
			}
			if (menuUrl.includes('/disclose')) {
				return 'bell';
			}
			if (menuUrl.includes('/visit')) {
				return 'team';
			}
		}
		return 'home'
	}
}
